// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.repo

import android.content.Context
import android.content.res.Configuration
import android.content.res.TypedArray
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.ColorUtils
import androidx.core.graphics.drawable.toBitmap
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.api.StopV1
import xyz.apiote.bimba.czwek.api.StopV2
import xyz.apiote.bimba.czwek.dpToPixelI
import java.util.zip.Adler32


data class Stop(
	val code: String,
	val name: String,
	val nodeName: String,
	val zone: String,
	val feedID: String?,
	val position: Position,
	val changeOptions: List<ChangeOption>
) : Queryable, Locatable {

	override fun icon(context: Context, scale: Float): Drawable {
		val md = Adler32().let {
			it.update(nodeName.toByteArray())
			it.value
		}
		val h = md % 359f
		val s = 1.0f
		val a: TypedArray = context.theme.obtainStyledAttributes(
			R.style.Theme_Bimba, intArrayOf(R.attr.randomColourLightness)
		)
		val l = a.getFloat(0, when (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
			Configuration.UI_MODE_NIGHT_YES -> 1f
			Configuration.UI_MODE_NIGHT_NO -> 0f
			Configuration.UI_MODE_NIGHT_UNDEFINED -> 0f
			else -> 0f
		})
		a.recycle()
		val bg = AppCompatResources.getDrawable(context, R.drawable.stop)!!.mutate().apply {
			setTint(ColorUtils.HSLToColor(floatArrayOf(h, s, l)))
		}
		return BitmapDrawable(
			context.resources,
			bg.toBitmap(dpToPixelI(24f / scale), dpToPixelI(24f / scale), Bitmap.Config.ARGB_8888)
		)
	}

	override fun id(): String = code

	override fun location(): Position = position

	constructor(s: StopV1) : this(
		s.code,
		s.name,
		s.name,
		s.zone,
		null,
		Position(s.position),
		s.changeOptions.map { ChangeOption(it) })

	constructor(s: StopV2) : this(
		s.code,
		s.name,
		s.nodeName,
		s.zone,
		s.feedID,
		Position(s.position),
		s.changeOptions.map { ChangeOption(it) })

	fun changeOptions(context: Context): Pair<String, String> = Pair(changeOptions.groupBy { it.line }
		.map { Pair(it.key, it.value.joinToString { co -> co.headsign }) }.joinToString {
			context.getString(
				R.string.vehicle_headsign, it.first, it.second
			)
		},
		changeOptions.groupBy { it.line }
			.map { Pair(it.key, it.value.joinToString { co -> co.headsign }) }.joinToString {
				context.getString(
					R.string.vehicle_headsign_content_description, it.first, it.second
				)
			})

	override fun toString(): String {
		var result = "$name ($code) [$zone] $position\n"
		for (chOpt in changeOptions) result += "${chOpt.line} → ${chOpt.headsign}\n"
		return result
	}
}